package com.wenhao.utils;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 可以用于限流
 * @author Wenhao Tong
 * @create 2021-08-20 11:52
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        // 线程数量
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0;i < 6;i++) {
            new Thread(() -> {
                try {
                    // 获得 相当于减一 如果已经为0 那么就等待
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "抢到车位");
                    TimeUnit.SECONDS.sleep(1);
                    System.out.println(Thread.currentThread().getName() + "离开车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    // 释放 加1
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }
    }
}
